<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/classes/SessionManager.class.php');

    class GroupWriteMutex {
    
        private static $GWRITE_MTX_NID = 0xff4322;
        
        private static $SESSION_KEY = 'GroupWMutex';
        
        static private $_semaphore = null;
        
        private function __construct() {
        }
        
        public static function initialize() {  
            self::$_semaphore = sem_get(self::$GWRITE_MTX_NID);
            SessionManager::registerVar(self::$SESSION_KEY,self::$_semaphore);
        }        
    
        public function acquireWriteAccess() {
            if (self::$_semaphore == null) {
                if (SessionManager::isVarSet(self::$SESSION_KEY)) {
                    self::$_semaphore = SessionManager::getVar(self::$SESSION_KEY);
                } else self::initialize();
            }
            return (self::$_semaphore != null) ? sem_acquire(self::$_semaphore) : null;
        }
        
        public function releaseWriteAccess() {
            SessionManager::clearVar(self::$SESSION_KEY);
            return (self::$_semaphore != null) ? sem_release(self::$_semaphore) : null;            
        }       
        
        private function __clone() {
        }
    
    }

?>
